import { Port } from "./models"

const validNodeIDRegex = /[a-zA-Z0-9.-]+-[a-zA-Z0-9.-]/
// const validEndpointIDRegex = /[a-zA-Z0-9.-]+-[a-zA-Z0-9.-]+-(input|output)+-[a-zA-Z0-9.-]/


export const parseNodeID = (nodeID: string) => {

    if (validNodeIDRegex.test(nodeID)) {
        const l = nodeID.split('-')
        return {
            nodeID: l[0],
            elID: nodeID
        }
    } else {
        // console.error()
        throw `Not valid node id ${nodeID}`
    }
}

export const parseEndpointID = (endpointID: string): Port => {
    if (validNodeIDRegex.test(endpointID)) {
        const l = endpointID.split('-')
        return {
            nodeID: l[0],
            nodeElID: l[0],
            direction: l[1], // 'input' or 'output'
            endpointID: l[2] // a number
        }
    } else {
        throw `Not valid Endpoint id ${endpointID}`
    }
}

export const toPortUUID = (nodeID: string, direction: string, portID: string) => {
    if (direction === "input" || direction === "output") {
        return nodeID + "-" + direction + "-" + portID;
    } else {
        throw `Direction ${direction}`
    }
}
export const portToEndpointUUID = (endpoint: Port) => {
    return toPortUUID(endpoint.nodeID, endpoint.direction, endpoint.endpointID)
}

export const toMidpointUUID = (edgeID: string, midpointIndex: number) => {
    return `midpoint-${edgeID}-${midpointIndex}`
}
export const parseMidpointUUID = (endpointUUID: string): { edgeID: string, index: number } => {
    if (!endpointUUID.startsWith('midpoint-')) {
        throw Error(`Invalid midpoint UUID ${endpointUUID}`)
    }

    const l = endpointUUID.split('-')
    return {
        edgeID: l[1],
        index: parseInt(l[2])
    }
}